import sys
import os
import pygame
from login import LoginScreen
from menu import MenuScreen
from game import GameScreen
from online_game import OnlineGameScreen
from db_manager import DatabaseManager

class GobangGame:
    def __init__(self):
        # 在初始化Pygame之前设置窗口位置
        # 这是确保窗口居中的最可靠方法
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        
        pygame.init()
        pygame.mixer.init()
        
        # 初始化数据库
        self.db_manager = DatabaseManager()
        try:
            if not self.db_manager.connect():
                print("警告：无法连接到数据库，游戏将使用本地模式运行")
        except Exception as e:
            print(f"数据库初始化错误: {e}")
            print("游戏将使用本地模式运行")
        
        # 设置窗口 - 增加窗口尺寸
        self.width, self.height = 900, 700  # 从800x600增加到900x700
        
        # 创建窗口 - 使用SHOWN标志确保窗口显示
        self.screen = pygame.display.set_mode((self.width, self.height), pygame.SHOWN)
        pygame.display.set_caption("五子棋游戏")
        
        # 设置图标
        try:
            icon_path = os.path.join("icon", "game.png")
            if os.path.exists(icon_path):
                pygame.display.set_icon(pygame.image.load(icon_path))
            else:
                print("图标不存在")
        except:
            pass
        
        # 状态管理
        self.current_screen = "login"  # 可以是 "login", "menu", "game" 或 "online_game"
        self.login_screen = None
        self.menu_screen = None
        self.game_screen = None
        self.online_game_screen = None
        self.username = ""
        self.game_mode = "local"  # 默认为本地对战模式
        
        # 初始化登录界面
        try:
            self.login_screen = LoginScreen(self)
            print("登录界面初始化成功")
        except Exception as e:
            print(f"初始化登录界面错误: {e}")
            sys.exit(1)
        
    def set_username(self, username):
        self.username = username
        
    def switch_to_menu(self):
        """从登录界面切换到菜单界面"""
        self.current_screen = "menu"
        self.menu_screen = MenuScreen(self)
    
    def return_to_menu(self):
        """从游戏界面返回菜单界面，并恢复原窗口大小"""
        # 如果有保存的菜单窗口大小，则恢复
        if hasattr(self, 'menu_width') and hasattr(self, 'menu_height'):
            # 重新设置窗口居中环境变量
            os.environ['SDL_VIDEO_CENTERED'] = '1'
            
            self.width, self.height = self.menu_width, self.menu_height
            
            # 创建新窗口
            self.screen = pygame.display.set_mode((self.width, self.height), pygame.SHOWN)
        
        # 切换到菜单界面
        self.current_screen = "menu"
        self.menu_screen = MenuScreen(self)
        
    def switch_to_game(self):
        """从菜单界面切换到游戏界面，并调整窗口大小"""
        # 保存当前窗口大小
        self.menu_width, self.menu_height = self.width, self.height
        
        # 重新设置窗口居中环境变量
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        
        # 调整为更大的游戏窗口，但只增加宽度和高度，不改变棋盘大小
        self.width, self.height = 1100, 850  # 进一步增加游戏界面的窗口大小
        
        # 创建新窗口并居中显示
        self.screen = pygame.display.set_mode((self.width, self.height), pygame.SHOWN)
        
        # 切换到游戏界面
        self.current_screen = "game"
        self.game_screen = GameScreen(self)
        
    def switch_to_online_game(self):
        """从菜单界面切换到网络对战界面，并调整窗口大小"""
        # 保存当前窗口大小
        self.menu_width, self.menu_height = self.width, self.height
        
        # 重新设置窗口居中环境变量
        os.environ['SDL_VIDEO_CENTERED'] = '1'
        
        # 调整为更大的游戏窗口，为聊天区域留出更多空间
        self.width, self.height = 1300, 850
        
        # 创建新窗口并居中显示
        self.screen = pygame.display.set_mode((self.width, self.height), pygame.SHOWN)
        
        # 切换到网络对战界面
        self.current_screen = "online_game"
        
        # 清理旧的网络连接资源（如果存在）
        if hasattr(self, 'online_game_screen') and self.online_game_screen:
            try:
                if hasattr(self.online_game_screen, 'network'):
                    self.online_game_screen.network.disconnect()
                    # 确保完全断开连接
                    pygame.time.delay(200)
            except Exception as e:
                print(f"清理旧连接资源时出错: {e}")
        
        # 确保完全释放旧实例
        self.online_game_screen = None
        
        # 创建新的网络对战界面实例
        print(f"创建新的网络游戏实例，用户名: {self.username}")
        self.online_game_screen = OnlineGameScreen(self)
    
    def run(self):
        clock = pygame.time.Clock()
        running = True
        
        try:
            while running:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        running = False
                    
                    
                    # 根据当前界面处理事件
                    if self.current_screen == "login" and self.login_screen:
                        self.login_screen.handle_event(event)
                    elif self.current_screen == "menu" and self.menu_screen:
                        self.menu_screen.handle_event(event)
                    elif self.current_screen == "game" and self.game_screen:
                        self.game_screen.handle_event(event)
                    elif self.current_screen == "online_game" and self.online_game_screen:
                        self.online_game_screen.handle_event(event)
                
                # 渲染当前界面
                if self.current_screen == "login" and self.login_screen:
                    self.login_screen.render()
                elif self.current_screen == "menu" and self.menu_screen:
                    self.menu_screen.render()
                elif self.current_screen == "game" and self.game_screen:
                    self.game_screen.render()
                elif self.current_screen == "online_game" and self.online_game_screen:
                    self.online_game_screen.render()
                
                pygame.display.flip()
                clock.tick(60)
        except Exception as e:
            print(f"游戏运行时错误: {e}")
            import traceback
            traceback.print_exc()
        finally:
            # 确保在退出时关闭数据库连接
            if hasattr(self, 'db_manager'):
                self.db_manager.close()
            pygame.quit()
            sys.exit()

if __name__ == "__main__":
    try:
        game = GobangGame()
        game.run()
    except Exception as e:
        print(f"程序启动错误: {e}")
        import traceback
        traceback.print_exc()
        sys.exit(1) 